import asyncio
from pyppeteer import launch


# api文档  https://github.com/GoogleChrome/puppeteer/blob/v1.18.1/docs/api.md#puppeteerlaunchoptions

async def run(url):
    brower = await launch({
        "headless": False  # 设置模式, 默认无头
    })
    # 打开新页面
    page = await brower.newPage()

    # 设置页面视图大小
    # await page.setViewport(viewport={'width': 1280, 'height': 800})

    # 是否启用JS，enabled设为False，则无渲染效果
    await page.setJavaScriptEnabled(enabled=True)

    print("默认UA", await brower.userAgent())
    # 设置当前页面UA
    await page.setUserAgent(
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36")

    # 打开路由
    await  page.goto(url)

    # 输入内容  不会写选择器可以直接选择标签copy js path
    await page.type("#key.text", "iphone")
    # 点击搜索
    await page.click("button.button")

    # 等待页面响应0.5S
    await asyncio.sleep(2)

    print("页面cookie", await page.cookies())
    print("页面标题", await page.title())
    print("页面内容", await page.content())

    # 截图
    await page.screenshot({'path': 'test.png'})

    # 滚动到页面底部
    await page.evaluate('window.scrollBy(0, window.innerHeight)')

    await brower.close()


loop = asyncio.get_event_loop()
loop.run_until_complete(run("https://jd.com"))